#! env python3

import sys, os, re
import shutil
import glob

def find_ln_point(path):
    if not path: return None
    if path.startswith("/"):
        return None
    path_list = path.split("/")
    temp_path = ""
    num_path_ele = len(path_list)
    for (idx, p) in enumerate(path_list):
        temp_path = os.path.join(temp_path, p)
        if os.path.islink(temp_path):
            return (temp_path, path_list[idx+1:])
    return None

def _imp_replace_dir(ln_point):
    ln_src = os.path.realpath(os.readlink(ln_point))
    assert(os.path.isdir(ln_src))
    files_in_src = os.listdir(ln_src)
    print("Info: entering directory -> \33[1m%s\33[0m"%ln_point)
    os.remove(ln_point)
    os.makedirs(ln_point)
    for f in files_in_src:
        file_to_link_src = os.path.join(ln_src, f)
        file_to_link_dest = os.path.join(ln_point, f)
        print(" ln %s -> %s"%(file_to_link_src, file_to_link_dest))
        os.symlink(file_to_link_src, file_to_link_dest)
    os.chdir(ln_point)

def _imp_replace_file(ln_point):
    ln_src = os.path.realpath(os.readlink(ln_point))
    assert(os.path.isfile(ln_src))
    print("Info: replace file \33[1m%s\33[0m"%ln_point)
    os.remove(ln_point)
    shutil.copyfile(ln_src, ln_point)
    
def replace(ln_point):
    ln_src = os.path.realpath(os.readlink(ln_point))
    if os.path.isdir(ln_src):
        _imp_replace_dir(ln_point)
    else:
        _imp_replace_file(ln_point)

def lnreplace(path):

    if not os.path.exists(path):
        print("Error: '%s' does not exist." %path)
        return
    cwd = os.getcwd()
    ln_info = find_ln_point(path)
    if ln_info:
        ln_point, rem_path_ele_list = ln_info
        assert(os.path.islink(ln_point))

        ln_src = os.path.realpath(os.readlink(ln_point))
        replace(ln_point)

        while rem_path_ele_list:
            p = rem_path_ele_list.pop(0)
            if p:
                replace(p)
    else:
        print("Warning: cannot find link point, or abs path is not support.")
    os.chdir(cwd)

if __name__ == "__main__":

    if (len(sys.argv)<2):
        print("Error: usage is \33[1m[lnreplace [diretory]]\33[0m.")
        sys.exit(0) 
    assert(len(sys.argv) >= 2);
    paths = sys.argv[1:]
    for p in paths:
        lnreplace(p)